/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package builder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.jar.JarFile;

import org.apache.commons.io.IOUtils;
import utils.Debug;

/**
 *
 * @author daz
 */
public class ApkBuilder {

    private String pathFolder;
    private String apkName;
    private String newName;
    public String datFileName = "info.dat";
    private static final byte[] BUFFER = new byte[4096 * 1024];
    private String desPath = "";

    public void setDesPath(String desPath) {
        this.desPath = desPath;
    }

    public void setApkName(String apkName) {
        this.apkName = apkName;
    }

    public void setNewApkName(String newName) {
        Debug.d("new name :" + newName);
        this.newName = newName;
    }

    public void setPathFolder(String pathFolder) {
        this.pathFolder = pathFolder + File.separator;
    }

    public void copyStream(InputStream input, OutputStream output) throws IOException {
        int bytesRead;
        while ((bytesRead = input.read(BUFFER)) != -1) {
            output.write(BUFFER, 0, bytesRead);
        }
    }

    public void createFile() {
        try {
            File output = null;
            JarFile originalFile = null;
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(ApkBuilder.class.getResourceAsStream("ApkSign.cer"));
            KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(IOUtils.toByteArray(ApkBuilder.class.getResourceAsStream("ApkSign.private"))));
            if (desPath.length() == 0) {
                output = new File(pathFolder + newName + ".apk");
                originalFile = new JarFile(pathFolder + apkName);
                SignApk signApk = new SignApk(pathFolder, "info.dat");
                signApk.sign(cert, privateKey, true, originalFile, output);
            } else {
                output = new File(desPath + newName + ".apk");
                Debug.d("out put :" + output.getAbsolutePath());
                originalFile = new JarFile(pathFolder + apkName);
                SignApk signApk = new SignApk(pathFolder, "info.dat");
                signApk.setDesPath(desPath);
                signApk.sign(cert, privateKey, true, originalFile, output);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
